// pages/gamedetail/gamedetail.js

const host = require('../../config.js').host;
const network = require('../../utils/network.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    timer: null,
    host: host,
    banlance: 0,
    nodes: "",
    seatSn: "",
    detailDic: {},
    seatList: [],
    couponList: [],
    deviceSn: "",
    customerPrizeIdList: [],
    seatSnList: [],
    seatName: '选择卡位',
    couponName: '选择优惠券',
    couponSelectIndex: -1,
    baseUrl: "",
    CouponModalAppear: false
  },

  getDetail() {

    let that = this;
    network.requestGet(host + '/xcx/device/getDeviceInfoBySeatSn', {
      "seatSn": that.data.seatSn,
    }, res => {
      if (res.data.code == 200) {
        console.log('=======' + res)
        var arr = res.data.data.seatList
        for (const i in arr) {
          if(arr[i].deviceSeatSn == that.data.seatSn&&arr[i].inuseStatus==0&&that.data.seatSnList.length==0){
            arr[i].checked = true
            that.setData({
              seatSnList: [that.data.seatSn]
            }) 
          }else{
            arr[i].checked = false
          }
          
        }

        that.setData({
          detailDic: res.data.data,
          seatList: arr
        })
        if (res.data.data.seatList.length) {

          that.setData({
            deviceSn: res.data.data.seatList[0].deviceSn
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg ? res.data.msg : '请求失败',
          icon: "none",
          duration: 1200
        })
      }
    })
  },
  getBanlance() {
    let that = this;
    network.requestGet(host + '/xcx/customer/getUserInfo', {}, res => {
      if (res.data.code == 200) {
        that.setData({
          banlance: res.data.data.balance,
        })
      }
    })
  },

  // 获取抵扣券列表
  getCouponList() {
    let that = this;
    network.requestGet(host + '/xcx/customer-prize/list', {
      "goodsType": 2,
      "prizeUseState": 0
    }, res => {
      console.log("优惠券" + res)
      if (res.data.code == 200) {
        var arr = res.data.data
        for (const i in arr) {
          if (i == 0 && arr[i].prizeUseState == 0) {
            arr[i].checked = false
            // that.setData({
            //   customerPrizeId: arr[i].customerPrizeId
            // })
          } else {
            arr[i].checked = false
          }

        }
        that.setData({
          couponList: arr,
        })
      } else {
        wx.showToast({
          title: res.data.msg ? res.data.msg : '请求失败',
          icon: "none",
          duration: 1200
        })
      }
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: ""
    })
  },
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)

    for (var i = 0; i < this.data.seatList.length; i++) {
      var seatSn = this.data.seatList[i].deviceSeatSn;

      if (seatSn == e.detail.value) {
        this.setData({
          seatName: "卡位" + this.data.seatList[i].seatNo,
          seatSn: e.detail.value,
          modalName: ""
        })
      }
    }


  },
  showCouponModal(e) {
    var theAppear = !this.data.CouponModalAppear;
    this.setData({
      CouponModalAppear: theAppear
    })
  },
  choseCouponBtn(e) {
    // console.log("优惠券："+e.currentTarget.dataset.index)
    this.setData({
      customerPrizeId: e.currentTarget.dataset.customerprizeid,
      couponSelectIndex: e.currentTarget.dataset.index,
      // CouponModalAppear:false
    })
  },
  hideCouponModal(e) {
    this.setData({
      modalName: ""
    })
  },
  couponChange: function (e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value)
    let couponList = this.data.couponList;
    for (var i = 0; i < this.data.seatList.length; i++) {
      var theId = this.data.couponList[i].customerPrizeId;
      couponList[i].checked = !couponList[i].checked
      if (theId == e.detail.value) {
        this.data.couponList[i].checked = !this.data.couponList[i].checked
        this.setData({
          couponName: this.data.couponList[i].goodsName,
          customerPrizeId: e.detail.value,
          modalName: "",
          couponList: couponList
        })
      }
    }

  },
  alertPayActionSheet() {
    let that = this;
    
    if (that.data.seatSnList.length == 0) {
      wx.showToast({
        title: '请选择游戏卡位',
        icon: 'none'
      })
      return;
    }
    wx.showActionSheet({
      itemList: ['余额支付', '充值', '微信支付'],
      itemColor:'#000000',
      success: function (res) {
        console.log("点击了列表项：" + res.tapIndex)
        if (res.tapIndex == 0) {
          that.getTotalPrice(true);
        } else if (res.tapIndex == 1) {
          wx.navigateTo({
            url: '/pages/recharge/recharge',
          })
        } else if (res.tapIndex == 2) {
          that.getTotalPrice(false);
        }
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },
  getTotalPrice(isBanlance){
    let that = this; 
    var seatIDs = that.data.seatSnList.join(",") 
    var customerPrizeIDs = that.data.customerPrizeIdList.join(",")
    network.requestPost(host + '/weiXinPayment/payBySeatSns', {
      "seatSns": seatIDs,
      "customerPrizeIds": customerPrizeIDs,
      "deviceSn": that.data.deviceSn,
      "balancePay": isBanlance,
      "actionType":0 //计算
    }, res => {
      console.log("根据卡位码支付=" + res)
      if (res.data.code == 200) {
        let totalPrice=res.data.payMoney;
        that.postPlayGameData(isBanlance,totalPrice);
      } else {
        wx.showToast({
          title: res.data.msg ? res.data.msg : '请求失败',
          icon: "none",
          duration: 2000
        })
      }
    })
  },
  // 根据卡位码支付
  postPlayGameData(isBanlance,totalPrice) {

    let that = this; 
    var seatIDs = that.data.seatSnList.join(",") 
    var customerPrizeIDs = that.data.customerPrizeIdList.join(",")
    if (isBanlance) { 
      if (totalPrice > that.data.banlance) {

        wx.showModal({
          title: '提示',
          content: '余额不足,是否去充值?',
          showCancel: true, //是否显示取消按钮
          cancelText: "取消", //默认是“取消”
          cancelColor: '#ff0000', //取消文字的颜色
          confirmText: "确定", //默认是“确定”
          confirmColor: '#000000', //确定文字的颜色
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              //点击确定
              wx.navigateTo({
                url: '/pages/recharge/recharge',
              })
            }
          },
          fail: function (res) {},
          complete: function (res) {},
        })

        return;
      }
      wx.showModal({
        title: totalPrice > 0 ? '是否支付' + totalPrice : '是否支付' + 0 + '元?',
        content: '当前账户余额:' + that.data.banlance + '元',
        showCancel: true, //是否显示取消按钮
        cancelText: "取消", //默认是“取消”
        cancelColor: '#ff0000', //取消文字的颜色
        confirmText: "确定", //默认是“确定”
        confirmColor: '#000000', //确定文字的颜色
        success(res) {
          if (res.confirm) {
            wx.requestSubscribeMessage({
              tmplIds: ['JGnHrsS0gWgJTXWgzVifO9AY5VH0gaeESIyDq4vIYFE','nV3vI_twgxGSWPQCYQq8ech3PkXpmaxmYN7TWgwMntw'],
              success(res) {}
            })
            network.requestPost(host + '/weiXinPayment/payBySeatSns', {
              "seatSns": seatIDs,
              "customerPrizeIds": customerPrizeIDs,
              "deviceSn": that.data.deviceSn,
              "balancePay": isBanlance,
              "actionType":1 //支付
            }, res => {
              console.log("根据卡位码支付=" + res)
              if (res.data.code == 200) {
                

                wx.showToast({
                  title: '支付成功',
                  duration: 2000
                }) 
        
        
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                  // that.setData({
                  //   seatSnList:[],
                  //   customerPrizeIdList:[]
                  // })
                  // that.getDetail()
                  // that.getCouponList()
                  // that.getBanlance()
                }, 2000);
              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '请求失败',
                  icon: "none",
                  duration: 2000
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })


    } else {
      wx.showModal({
        title: totalPrice > 0 ? '是否使用微信支付' + totalPrice + '元?': '是否使用微信支付' + 0 + '元?',
        content: '',
        showCancel: true, //是否显示取消按钮
        cancelText: "取消", //默认是“取消”
        cancelColor: '#ff0000', //取消文字的颜色
        confirmText: "确定", //默认是“确定”
        confirmColor: '#000000', //确定文字的颜色
        success(res) {
          if (res.confirm) {
            wx.requestSubscribeMessage({
              tmplIds: ['JGnHrsS0gWgJTXWgzVifO9AY5VH0gaeESIyDq4vIYFE','nV3vI_twgxGSWPQCYQq8ech3PkXpmaxmYN7TWgwMntw'],
              success(res) {}
            })
            network.requestPost(host + '/weiXinPayment/payBySeatSns', {
              "seatSns": seatIDs,
              "customerPrizeIds": customerPrizeIDs,
              "deviceSn": that.data.deviceSn,
              "balancePay": isBanlance,
              "actionType":1 //zhifu
            }, res => {
              console.log("根据卡位码支付=" + res)
      
              if (res.data.code == 200) {
                if (res.data.h5PayArgs) {
                  that.gotopay(res.data.h5PayArgs)
                } else {
                  
                  wx.showToast({
                    title: '支付成功',
                    duration: 2000
                  })
                  setTimeout(() => {
                    wx.switchTab({
                      url: '/pages/index/index',
                    })
                    // that.setData({
                    //   seatSnList:[],
                    //   customerPrizeIdList:[]
                    // })
                    // that.getDetail()
                    // that.getCouponList()
                  
                  }, 2000);
                  
                } 
      
              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '请求失败',
                  icon: "none",
                  duration: 2000
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })
      
      
    }
  },

  gotopay(e) {
    let that = this;

    wx.requestPayment({
      signType: e.signType,
      timeStamp: e.timeStamp,
      nonceStr: e.nonceStr,
      package: e.package,
      paySign: e.paySign,
      success(res) {
        console.log('成功：' + res)

         
        wx.showToast({
          title: '支付成功',
          duration: 2000
        }) 


        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index',
          })
          // that.setData({
          //   seatSnList:[],
          //   customerPrizeIdList:[]
          // })
          // that.getDetail()
          // that.getCouponList()
        
        }, 2000);
      },
      fail(res) {
        console.log('失败：' + res)
        wx.showToast({
          title: '支付失败',
          duration: 3000
        })
      },
      complete(res) {

      }
    })
  },

  checkboxChange(e) {

    this.setData({
      seatSnList: e.detail.value
    }) 
    console.log(this.data.seatSnList)
  },
  checkboxCouponChange(e) {
    
    // this.setData({
    //   customerPrizeIdList: e.detail.value
    // })
    // console.log(this.data.customerPrizeIdList)
  },
  checkedCouponTap: function (e) {

    let couponList = this.data.couponList;
    let customerPrizeIdList = this.data.customerPrizeIdList;
    
    var index = e.currentTarget.dataset.index;
    var checked = couponList[index].checked;
    let customerPrizeId = couponList[index].customerPrizeId;

    if (customerPrizeIdList.indexOf(customerPrizeId)!==-1) {
      couponList[index].checked = false; 
      let  theindex=customerPrizeIdList.indexOf(customerPrizeId)
        customerPrizeIdList.splice(theindex,1);
         this.setData({
          couponList: couponList,
          customerPrizeIdList: customerPrizeIdList
        })
      
    }else{
      if(customerPrizeIdList.length==this.data.seatSnList.length){
        wx.showToast({
          title: '超过最大选择数量',
        })
        couponList[index].checked = false;  
         this.setData({
          couponList: couponList
        })
      }else{
        couponList[index].checked = true; 
        customerPrizeIdList.push(customerPrizeId);
         this.setData({
          couponList: couponList,
          customerPrizeIdList: customerPrizeIdList
        })
      }
      
    }

    console.log('couponList=',this.data.couponList)
    console.log('customerPrizeIdList=',this.data.customerPrizeIdList)

     
    // console.log('customerPrizeId=', this.data.customerPrizeId)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      baseUrl: host
    })

    const scene = decodeURIComponent(options.scene)
    // deviceSeatSn=

    if (options.deviceSeatSn || options.seatSn) {
      if (options.deviceSeatSn) {
        this.setData({
          seatSn: options.deviceSeatSn
        })
      } else if (options.seatSn) {
        this.setData({
          seatSn: options.seatSn
        })
      }



    } else {
      var arr = scene.split('&')
      for (const str in arr) {
        if (scene) {



          var arr = scene.split('&')

          for (const inde in arr) {
            console.log(arr[inde])
            var str = arr[inde]
            console.log(str)
            if (str.indexOf('deviceSeatSn=') == 0) {
              var newStr = str.replace(/deviceSeatSn=/, '')

              this.setData({
                seatSn: newStr
              })
            }
          }

        }
      }

    }

    this.getDetail()
    this.getCouponList()
    this.getBanlance()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let _this = this;
    // this.setData({
    //   timer: setInterval(() => {
    //     _this.setTimeCount()
    //   }, 5000)
    // })
  },
  // 定时器
  setTimeCount: function () {
    this.getDetail();
    // let time = this.data.time
    // time--;
    // if (time <= 0) {
    //   wx.redirectTo({
    //     url: '/pages/index/index'
    //   })
    //   return false;
    // }
    // this.setData({
    //   time: time,
    // })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // clearInterval(this.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})